<?php
namespace app\openapi\controller;
use think\Controller;
use think\Db;

use app\model\ApiToken as TokenModel;

class Base extends Controller
{
    public $login_user = [];
    protected $noCheckToken = ['getToken'];

    public function __construct(){
        parent::__construct();
        // 验证token
        $action = $this->request->action();
        if (!empty($this->noCheckToken)) {
            $noCheckToken = array_map('strtolower',$this->noCheckToken);
        }else{
            $noCheckToken = [];
        }
        $access_token = input('access_token');
        // $access_token = '340D44A6C24D4B02B99BB4950A7999AB';
        if ( !in_array($action, $noCheckToken) || !empty($access_token) ) {
            if ( empty($access_token) ) {
                exception('token不能为空',9000);
            }
            $token = TokenModel::where('access_token',$access_token)->find();
            if ( empty($token) ) {
                exception('token无效',9000);
            }
            if ( time() > strtotime($token['expiry_time']) ) {
                // exception('token已过期',9000);
            }

            $this->login_user = [
                'user_id'=>$token['user_id']
            ];
        }
    }

    public function getToken(){
        $param = file_get_contents('php://input');
        $param = json_decode($param,true);

        $fields = [
            'must'=>['api_key','ts','sign']
        ];
        $params = paramFilter($param,$fields);
        if (!empty($params['error_msg'])) {
            return apiResult(5000,$params['error_msg']);
        }
        if (time() - $params['ts'] > 60) {
            return apiResult(5000,'时间戳无效或已超时');
        }

        $uinfo = Db::name('user')->where('api_key',$params['api_key'])->find();
        if (empty($uinfo)) {
            return apiResult(5000,'API KEY无效');
        }

        $sign = md5($params['api_key'].$params['ts'].$uinfo['api_secret']);
        if  ($sign != $params['sign']) {
            return apiResult(5000,'签名无效');
        }

        // 生成token
        $token_data = [
            'user_id'=>$uinfo['id'],
            'access_token'=>uuidCreate(),
            'expiry_time'=>date('Y-m-d H:i:s',strtotime('+7 days')),
        ];
        TokenModel::where('user_id',$uinfo['id'])->delete(); // 删除旧的token
        if ( !TokenModel::insert($token_data) ) {
            return apiResult(5000,'token生成失败');
        }
        
        return apiResult('2000','登录成功',$token_data);
    }



}
